<template>
  <div class="all">
    <el-checkbox
      :indeterminate="indeterminate"
      v-model="isCheckAll"
      @change="handleCheckAllChange">
      {{ node.name }}
    </el-checkbox>
    <div>
      <el-checkbox-group
        v-model="checkeds"
        class="item-group"
        @change="handleCheckChange">
        <el-checkbox
          v-for="child in node.userList"
          :label="child.id"
          :key="child.id"
          class="item">
          {{ child.realName }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TwoCheckItem',
  props: {
    // eslint-disable-next-line vue/require-prop-types
    node: {
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      indeterminate: false,
      isCheckAll: false,
      checkeds: [],
      allIds: []
    };
  },
  created() {
    this.initIds();
  },
  methods: {
    // 全选
    handleCheckAllChange(value) {
      this.indeterminate = false;
      this.checkeds = value ? this.allIds : [];
      this.check();
    },
    // 手动选择
    handleCheckChange(value, ev) {
      this.check();
      this.indeterminate = false;
      if (value.length === 0) {
        this.isCheckAll = false;
        return;
      }
      if (value.length === this.allIds.length) {
        this.isCheckAll = true;
        return;
      }
      this.indeterminate = true;
    },
    check() {
      this.$emit('check', this.node.id, this.checkeds);
    },

    // 初始化ID
    initIds() {
      const userList = this.node.userList;
      if (!userList) {
        return;
      }
      userList.map(user => {
        this.allIds.push(user.id);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .all {
    margin: 20px;
  }

  .item-group {
    padding-left: 30px;

    .item {
      padding: 10px;
    }
  }
</style>
